# -*- coding: utf-8 -*-
import re
from rest_framework import serializers
from datetime import datetime,time
from datetime import timedelta
from rest_framework.validators import UniqueValidator

from .models import AuthCode, User

from tuntun.settings import REGEX_MOBILE


class SmsSerializer(serializers.Serializer):
    """
    验证码
    """
    mobile = serializers.CharField(max_length=11)

    def validate_mobile(self, mobile):
        """
        验证手机号码
        :param data:
        :return:
        """

        # 验证手机号码是否合法
        if not re.match(REGEX_MOBILE, mobile):
            raise serializers.ValidationError("手机号码非法")

        # 验证码发送频率

        return mobile


class UserDetailSerializer(serializers.ModelSerializer):
    """
    用户详情
    """
    class Meta:
        model = User
        fields = "__all__"


class UserLoginSerializer(serializers.ModelSerializer):
    """
    用户 登陆 注册
    """
    code = serializers.CharField(required=True, write_only=True, max_length=4, min_length=4, label="验证码",
                                 error_messages={
                                     "blank": "请输入验证码",
                                     "required": "请输入验证码",
                                     "max_length": "验证码格式错误",
                                     "min_length": "验证码格式错误"
                                 },
                                 help_text="验证码")


    def update(self, instance, validated_data):
        user = super(UserLoginSerializer, self).update(validated_data=validated_data)
        user.save()

    def validate_code(self, code):
        ver_cord = AuthCode.objects.filter(mobile=self.initial_data["mobile"]).order_by("-expire_at")
        try:
            if ver_cord:
                last_code = ver_cord[0]
            else:
                raise serializers.ValidationError("验证码错误")
        except AuthCode.DoesNotExist as en:
            raise serializers.ValidationError("验证码错误")
        except Exception as e:
            raise serializers.ValidationError("验证码错误")

        #验证过期时间
        #nowtime =time.time()
        # if nowtime > last_code.expire_at:
        #     raise serializers.ValidationError("验证码过期")

        if last_code.code != code:
            raise serializers.ValidationError("验证码错误")

        def validate(self, attrs):
            attrs["nickname"] = attrs["mobile"]
            del attrs["code"]
            return attrs

    class Meta:
        model = User
        fields = ("mobile", "code")

